<template>
  <div class="main relative h-full min-h-[720px] min-w-[1560px]">
    <div class="absolute left-[64px] top-[64px]">
      <img src="@/assets/images/logo-login.png" class="h-[54px] w-[448px]" />
    </div>
    <div class="absolute right-[245px] top-1/2 h-[600px] w-[560px] -translate-y-1/2">
      <div
        class="absolute right-0 top-1/2 box-border flex h-[600px] w-[560px] -translate-y-1/2 flex-col rounded-[4px] bg-[#FFF]"
      >
        <div class="mb-[66px] ml-[80px] mt-[80px] flex">
          <template v-if="!forgotPassword">
            <div
              v-for="(item, index) in tabList"
              :key="index"
              class="relative mr-[32px] cursor-pointer"
              @click="onTabClick(index)"
            >
              <div
                class="h-[28px] text-[20px] leading-[28px]"
                :class="tabIndex == index ? 'font-semibold text-[#363F51]' : 'font-normal text-[#959EB2]'"
              >
                {{ item.label }}
              </div>
              <div
                :class="
                  tabIndex == index
                    ? 'absolute left-1/2 mt-[6px] h-[4px] w-[32px] -translate-x-1/2 rounded-[2px] bg-[#1D7FF2]'
                    : ''
                "
              ></div>
            </div>
          </template>
          <template v-else>
            <div class="relative mr-[32px] cursor-pointer">
              <div class="h-[28px] text-[20px] font-semibold leading-[28px] text-[#363F51]">忘记密码</div>
              <div
                class="absolute left-1/2 mt-[6px] h-[4px] w-[32px] -translate-x-1/2 rounded-[2px] bg-[#1D7FF2]"
              ></div>
            </div>
          </template>
        </div>
        <div class="flex-1">
          <template v-if="tabIndex == 0 && !forgotPassword">
            <el-form
              ref="loginForm"
              :model="loginForm"
              :rules="loginFormRules"
              autocomplete="on"
              class="h-full text-center"
            >
              <el-form-item
                key="loginUsername"
                prop="username"
                class="relative left-1/2 !mb-[20px] !mr-0 w-[400px] -translate-x-1/2"
              >
                <el-input v-model.trim="loginForm.username" autocomplete="on" placeholder="请输入用户名">
                  <template #prefix>
                    <div class="relative top-1/2 ml-[16px] -translate-y-1/2">
                      <img src="@/assets/images/icon-user.png" class="h-[22px] w-[20px]" />
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                key="loginPassword"
                prop="password"
                class="relative left-1/2 !mb-[20px] !mr-0 mt-[20px] w-[400px] -translate-x-1/2"
              >
                <el-input
                  v-model.trim="loginForm.password"
                  autocomplete="on"
                  placeholder="请输入密码"
                  :type="type"
                  @keyup.enter.native="handleLogin"
                >
                  <template #prefix>
                    <div class="relative top-1/2 ml-[16px] -translate-y-1/2">
                      <img src="@/assets/images/icon-lock.png" class="h-[22px] w-[20px]" />
                    </div>
                  </template>
                  <template #suffix>
                    <div class="relative top-1/2 mr-[16px] -translate-y-1/2 cursor-pointer" @click="onChangePassword">
                      <img
                        :src="[
                          type == 'password'
                            ? require('@/assets/images/icon-password.png')
                            : require('@/assets/images/icon-password-show.png'),
                        ]"
                        :class="[type == 'password' ? 'h-[22px] w-[22px]' : 'h-[14px] w-[22px]']"
                      />
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item class="!mx-[80px] !mb-0 mt-[20px]">
                <div class="flex items-center justify-between">
                  <div class="flex items-center" @click="onRememberPassword">
                    <img
                      v-if="rememberPassword"
                      src="@/assets/images/icon_rememberPassword.png"
                      class="h-[16px] w-[16px]"
                    />
                    <div
                      v-else
                      class="h-[16px] w-[16px] rounded-[2px] border-[1px] border-solid border-[#BAC3D3]"
                    ></div>
                    <div class="ml-[8px] h-[20px] cursor-pointer text-[14px] font-normal leading-[20px] text-[#959EB2]">
                      记住密码
                    </div>
                  </div>
                  <div
                    class="h-[20px] cursor-pointer text-[14px] font-normal leading-[20px] text-[#959EB2]"
                    @click="onForgotPassword"
                  >
                    忘记密码？
                  </div>
                </div>
              </el-form-item>
              <el-form-item class="login-wrapper !mb-0 !mr-0 mt-[142px]">
                <t-button
                  type="primary"
                  class="w-full transition-none"
                  :loading="loading"
                  @click.native.prevent="handleLogin"
                  >登 录</t-button
                >
              </el-form-item>
            </el-form>
          </template>
          <template v-if="tabIndex == 1 && !forgotPassword">
            <el-form
              ref="codeLoginForm"
              :model="codeLoginForm"
              :rules="codeLoginFormRules"
              autocomplete="on"
              class="h-full text-center"
            >
              <el-form-item
                key="codeLoginUsername"
                prop="codeUsername"
                class="relative left-1/2 !mb-[20px] !mr-0 w-[400px] -translate-x-1/2"
              >
                <el-input v-model.trim="codeLoginForm.codeUsername" autocomplete="on" placeholder="请输入手机号码">
                  <template #prefix>
                    <div class="relative top-1/2 ml-[16px] -translate-y-1/2">
                      <img src="@/assets/images/icon-user.png" class="h-[22px] w-[20px]" />
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                key="codeLoginPassword"
                prop="codeLogin"
                class="relative left-1/2 !mb-0 !mr-0 mt-[20px] w-[400px] -translate-x-1/2"
              >
                <el-input
                  v-model.trim="codeLoginForm.codeLogin"
                  autocomplete="on"
                  placeholder="请输入短信验证码"
                  type="text"
                  @keyup.enter.native="handleCodeLogin"
                >
                  <template #prefix>
                    <div class="relative top-1/2 ml-[16px] -translate-y-1/2">
                      <img src="@/assets/images/icon_code.png" class="h-[22px] w-[20px]" />
                    </div>
                  </template>
                  <template #append>
                    <div
                      v-if="codeShow"
                      class="h-[56px] w-[128px] cursor-pointer rounded-[2px] bg-[#1D7FF2] text-center text-[16px] font-normal leading-[56px] text-[#FFFFFF]"
                      @click="sendLoginCode"
                    >
                      获取验证码
                    </div>
                    <div
                      v-if="!codeShow"
                      class="h-[56px] w-[128px] cursor-not-allowed rounded-[2px] bg-[#1D7FF2] text-center text-[16px] font-normal leading-[56px] text-[#FFFFFF]"
                    >
                      {{ codeCount }}秒后重试
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item class="login-wrapper !mb-0 !mr-0 mt-[182px]">
                <t-button
                  type="primary"
                  class="w-full transition-none"
                  :loading="codeLoading"
                  @click.native.prevent="handleCodeLogin"
                  >登 录</t-button
                >
              </el-form-item>
            </el-form>
          </template>
          <template v-if="forgotPassword">
            <el-form
              ref="forgotForm"
              :model="forgotForm"
              :rules="forgotFormRules"
              autocomplete="on"
              class="h-full text-center"
            >
              <el-form-item
                key="forgotUsername"
                prop="forgotUsername"
                class="relative left-1/2 !mb-[20px] !mr-0 w-[400px] -translate-x-1/2"
              >
                <el-input v-model.trim="forgotForm.forgotUsername" autocomplete="on" placeholder="请输入手机号码">
                  <template #prefix>
                    <div class="relative top-1/2 ml-[16px] -translate-y-1/2">
                      <img src="@/assets/images/icon-user.png" class="h-[22px] w-[20px]" />
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                key="forgotCode"
                prop="forgotCode"
                class="relative left-1/2 !mb-[20px] !mr-0 mt-[20px] w-[400px] -translate-x-1/2"
              >
                <el-input
                  v-model.trim="forgotForm.forgotCode"
                  autocomplete="on"
                  placeholder="请输入短信验证码"
                  type="text"
                >
                  <template #prefix>
                    <div class="relative top-1/2 ml-[16px] -translate-y-1/2">
                      <img src="@/assets/images/icon_code.png" class="h-[22px] w-[20px]" />
                    </div>
                  </template>
                  <template #append>
                    <div
                      v-if="codeForgotShow"
                      class="h-[56px] w-[128px] cursor-pointer rounded-[2px] bg-[#1D7FF2] text-center text-[16px] font-normal leading-[56px] text-[#FFFFFF]"
                      @click="sendForgotCode"
                    >
                      获取验证码
                    </div>
                    <div
                      v-if="!codeForgotShow"
                      class="h-[56px] w-[128px] cursor-not-allowed rounded-[2px] bg-[#1D7FF2] text-center text-[16px] font-normal leading-[56px] text-[#FFFFFF]"
                    >
                      {{ codeForgotCount }}秒后重试
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                key="forgetPassword"
                prop="forgetPassword"
                class="relative left-1/2 !mb-[20px] !mr-0 mt-[20px] w-[400px] -translate-x-1/2"
              >
                <el-input
                  v-model.trim="forgotForm.forgetPassword"
                  autocomplete="on"
                  placeholder="请输入新密码"
                  :type="forgotType"
                >
                  <template #prefix>
                    <div class="relative top-1/2 ml-[16px] -translate-y-1/2">
                      <img src="@/assets/images/icon-lock.png" class="h-[22px] w-[20px]" />
                    </div>
                  </template>
                  <template #suffix>
                    <div
                      class="relative top-1/2 mr-[20px] -translate-y-1/2 cursor-pointer"
                      @click="onChangeForgotPassword"
                    >
                      <img
                        :src="[
                          forgotType == 'password'
                            ? require('@/assets/images/icon-password.png')
                            : require('@/assets/images/icon-password-show.png'),
                        ]"
                        :class="[forgotType == 'password' ? 'h-[22px] w-[22px]' : 'h-[14px] w-[22px]']"
                      />
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item
                key="forgetNewPassword"
                prop="forgetNewPassword"
                class="relative left-1/2 !mb-0 !mr-0 mt-[20px] w-[400px] -translate-x-1/2"
              >
                <el-input
                  v-model.trim="forgotForm.forgetNewPassword"
                  autocomplete="on"
                  placeholder="请确认新密码"
                  :type="forgotNewType"
                  @keyup.enter.native="handleForgot"
                >
                  <template #prefix>
                    <div class="relative top-1/2 ml-[16px] -translate-y-1/2">
                      <img src="@/assets/images/icon-lock.png" class="h-[22px] w-[20px]" />
                    </div>
                  </template>
                  <template #suffix>
                    <div
                      class="relative top-1/2 mr-[20px] -translate-y-1/2 cursor-pointer"
                      @click="onChangeForgotNewPassword"
                    >
                      <img
                        :src="[
                          forgotNewType == 'password'
                            ? require('@/assets/images/icon-password.png')
                            : require('@/assets/images/icon-password-show.png'),
                        ]"
                        :class="[forgotNewType == 'password' ? 'h-[22px] w-[22px]' : 'h-[14px] w-[22px]']"
                      />
                    </div>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item class="login-wrapper !mb-0 !mr-0 mt-[30px]">
                <div class="mx-[80px] flex justify-between">
                  <div
                    class="mr-[25px] box-border h-[56px] w-[188px] cursor-pointer rounded-[4px] border-[1px] border-solid border-[#1D7FF2] bg-[#FFFFFF] text-center text-[20px] font-semibold leading-[56px] text-[#1D7FF2]"
                    @click="onCancle"
                  >
                    取 消
                  </div>
                  <t-button
                    type="primary"
                    class="!w-[188px] transition-none"
                    :loading="forgotLoading"
                    @click.native.prevent="handleForgot"
                    >保 存</t-button
                  >
                </div>
              </el-form-item>
            </el-form>
          </template>
        </div>
      </div>
    </div>
    <div class="absolute bottom-[80px] left-[35px] text-center">
      <img src="@/assets/images/app.png" class="h-[120px] w-[120px]" />
      <div class="mt-[10px] font-medium text-[#000]">扫码下载APP</div>
    </div>
    <div class="copyright">
      <a href="http://beian.miit.gov.cn" target="_blank">鄂ICP备2024049778号</a>
    </div>
  </div>
</template>

<script>
import storage from "@/util/storage";
import { messageError, messageSuccess } from "@/util/element-ui";
import { systemLoginForgetPassword, systemLoginSendSms } from "@/api/user-login";
export default {
  name: "Login",
  components: {},
  props: {},
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else {
        if (this.forgotForm.forgetNewPassword !== "") {
          this.$refs.forgotForm.validateField("forgetNewPassword");
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认新密码"));
      } else if (value !== this.forgotForm.forgetPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      tabIndex: 0,
      tabList: [{ label: "密码登录" }, { label: "短信登录" }],
      rememberPassword: storage.local.get("isRememberPassword") == "1" ? true : false, //是否记住密码
      forgotPassword: false,
      type: "password",
      loginForm: {
        username: storage.local.get("rememberUsername"),
        password: storage.local.get("rememberPassword"),
      },
      loginFormRules: {
        username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
        password: [
          { required: true, trigger: "blur", message: "请输入密码" },
          { min: 6, max: 20, trigger: "blur", message: "密码长度在6到20个字符之间" },
        ],
      },
      loading: false,

      codeLoginForm: {
        codeUsername: "",
        codeLogin: "",
      },
      codeLoginFormRules: {
        codeUsername: [
          { required: true, trigger: "blur", message: "请输入手机号码" },
          { trigger: "blur", pattern: /^1[3-9]\d{9}$/, message: "请输入正确手机号码" },
        ],
        codeLogin: [{ required: true, trigger: "blur", message: "请输入短信验证码" }],
      },
      codeShow: true,
      codeCount: "",
      codeTimer: null,
      codeLoading: false,

      forgotForm: {
        forgotUsername: "",
        forgotCode: "",
        forgetPassword: "",
        forgetNewPassword: "",
      },
      forgotFormRules: {
        forgotUsername: [
          { required: true, trigger: "blur", message: "请输入手机号码" },
          { trigger: "blur", pattern: /^1[3-9]\d{9}$/, message: "请输入正确手机号码" },
        ],
        forgotCode: [{ required: true, trigger: "blur", message: "请输入短信验证码" }],
        forgetPassword: [{ validator: validatePass, trigger: "blur" }],
        forgetNewPassword: [{ validator: validatePass2, trigger: "blur" }],
      },
      codeForgotShow: true,
      codeForgotCount: "",
      codeForgotTimer: null,
      forgotLoading: false,
      forgotType: "password",
      forgotNewType: "password",
    };
  },
  watch: {
    $route: {
      handler(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  destroyed() {
    clearInterval(this.codeTimer);
    clearInterval(this.codeForgotTimer);
  },
  methods: {
    sendForgotCode() {
      this.$refs.forgotForm.validateField("forgotUsername", async (errorMsg) => {
        if (!errorMsg) {
          await systemLoginSendSms({ code: this.forgotForm.forgotUsername });
          const TIME_COUNT = 60;
          if (!this.codeForgotTimer) {
            this.codeForgotCount = TIME_COUNT;
            this.codeForgotShow = false;
            this.codeForgotTimer = setInterval(() => {
              if (this.codeForgotCount > 0 && this.codeForgotCount <= TIME_COUNT) {
                this.codeForgotCount--;
              } else {
                this.codeForgotShow = true;
                clearInterval(this.codeForgotTimer);
                this.codeForgotTimer = null;
              }
            }, 1000);
          }
        } else {
          return false;
        }
      });
    },
    onTabClick(index) {
      this.tabIndex = index;
    },
    onRememberPassword() {
      this.rememberPassword = !this.rememberPassword;
    },
    onForgotPassword() {
      this.forgotPassword = true;
    },
    sendLoginCode() {
      this.$refs.codeLoginForm.validateField("codeUsername", async (errorMsg) => {
        if (!errorMsg) {
          await systemLoginSendSms({ code: this.codeLoginForm.codeUsername });
          const TIME_COUNT = 60;
          if (!this.codeTimer) {
            this.codeCount = TIME_COUNT;
            this.codeShow = false;
            this.codeTimer = setInterval(() => {
              if (this.codeCount > 0 && this.codeCount <= TIME_COUNT) {
                this.codeCount--;
              } else {
                this.codeShow = true;
                clearInterval(this.codeTimer);
                this.codeTimer = null;
              }
            }, 1000);
          }
        } else {
          return false;
        }
      });
    },
    onChangePassword() {
      if (this.type == "text") {
        this.type = "password";
      } else {
        this.type = "text";
      }
    },
    onChangeForgotPassword() {
      if (this.forgotType == "text") {
        this.forgotType = "password";
      } else {
        this.forgotType = "text";
      }
    },
    onChangeForgotNewPassword() {
      if (this.forgotNewType == "text") {
        this.forgotNewType = "password";
      } else {
        this.forgotNewType = "text";
      }
    },
    onCancle() {
      this.tabIndex = 0;
      this.forgotPassword = false;
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid, invalidFields) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              this.loading = false;
              storage.local.set("login_account", this.loginForm.username);
              //记住密码 start
              if (this.rememberPassword) {
                storage.local.set("isRememberPassword", 1);
                storage.local.set("rememberUsername", this.loginForm.username);
                storage.local.set("rememberPassword", this.loginForm.password);
              } else {
                storage.local.set("isRememberPassword", 0);
                storage.local.set("rememberUsername", "");
                storage.local.set("rememberPassword", "");
              }
              //记住密码 end
              this.$router.push({ path: this.redirect || "/" });
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          const message = Object.values(invalidFields)?.[0]?.[0]?.message;
          messageError(message);
        }
      });
    },
    //短信登录
    async handleCodeLogin() {
      this.$refs.codeLoginForm.validate((valid, invalidFields) => {
        if (valid) {
          this.codeLoading = true;
          this.$store
            .dispatch("user/loginCode", {
              mobile: this.codeLoginForm.codeUsername,
              verifyCode: this.codeLoginForm.codeLogin,
            })
            .then(() => {
              this.codeLoading = false;
              storage.local.set("login_account", this.codeLoginForm.codeUsername);
              this.$router.push({ path: this.redirect || "/" });
            })
            .catch(() => {
              this.codeLoading = false;
            });
        } else {
          const message = Object.values(invalidFields)?.[0]?.[0]?.message;
          messageError(message);
        }
      });
    },
    //忘记密码
    handleForgot() {
      this.$refs.forgotForm.validate(async (valid, invalidFields) => {
        if (valid) {
          try {
            this.forgotLoading = true;
            await systemLoginForgetPassword({
              mobile: this.forgotForm.forgotUsername,
              verifyCode: this.forgotForm.forgotCode,
              newPassword: this.forgotForm.forgetPassword,
              confirmPassword: this.forgotForm.forgetNewPassword,
            });
            this.forgotLoading = false;
            messageSuccess("操作成功");
            this.onCancle();
          } catch {
            this.forgotLoading = false;
          }
        } else {
          const message = Object.values(invalidFields)?.[0]?.[0]?.message;
          messageError(message);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  background: transparent url("@/assets/images/logo.png") no-repeat 0 0;
  background-size: cover;
}

.copyright {
  position: absolute;
  bottom: 20px;
  width: 100%;
  font-size: 14px;
  font-weight: 500;
  color: #000;
  text-align: center;

  a:hover {
    color: #000;
  }
}

::v-deep .el-input input {
  height: 56px;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 52px;
  font-size: 16px;
  background: #f3f4f9;
  border: none;
  border-radius: 2px !important;
}

::v-deep .el-input .el-input__inner {
  &::placeholder {
    height: 24px;
    font-size: 16px;
    font-weight: 400;
    line-height: 24px;
    color: #959eb2;
  }
}

::v-deep .el-form-item__content {
  font-size: 14px;
  line-height: 56px;
}

::v-deep .el-input {
  font-size: 14px;
}

::v-deep .el-form-item__content button {
  position: relative;
  width: 400px;
  height: 56px;
  background: #165dff;
  border: none;
  border-radius: 4px;
  box-shadow: 0 5px 20px 0 rgb(22 93 255 / 0.2);

  span {
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 20px;
    font-weight: 600;
    color: #fff;
    transform: translate(-50%, -50%);
  }
}

::v-deep .el-input-group__append {
  padding-right: 0;
  padding-left: 16px;
  background: transparent;
  border: none;
}

::v-deep .el-input__prefix {
  left: 0;
}

::v-deep .el-input__suffix {
  right: 0;
}

::v-deep .login-wrapper {
  .el-form-item__content {
    height: 56px;

    button {
      width: 400px;
    }
  }
}

::v-deep .el-form-item {
  margin-right: 12px;
  margin-bottom: 16px;
}

::v-deep .common-search-btn {
  display: inline-flex;
  align-items: center;
  height: 32px;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 0;
}

::v-deep .el-form-item__error {
  position: absolute;
  top: 100%;
  left: 0;
  padding-top: 4px;
  font-size: 12px;
  line-height: 1;
  color: #f56c6c;
}
</style>
